/**
 * 
 */
package scan;


import java.io.PrintWriter;
import java.util.Date;

import jcifs.smb.SmbAuthException;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import org.hibernate.Session;
import util.HibernateUtil;
import bean.NetResources;

/**
 * @author Max Areshkau
 * 
 */
public class OneComputerThread extends Thread {

	private SmbFile root;
	private Session session;
	private PrintWriter out;

	/**
	 * @param root
	 */
	public OneComputerThread(SmbFile root,PrintWriter out) {
		this.root = root;
		session = HibernateUtil.getSessionFactory().openSession();
		this.out=out;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Thread#run()
	 */
	@Override
	public void run() {
			session.beginTransaction();
			clean();
			recursia(root);
			session.getTransaction().commit();
			session.close();
	}

	public void recursia(SmbFile file) {
		try {
			SmbFile files[] = new SmbFile[0];
			try {
			files= file.listFiles();
			} catch (SmbAuthException ex) {
				file = new SmbFile(file.getCanonicalPath());
				files= file.listFiles();
			}
			for (SmbFile element : files) {
				if (element.isDirectory()) {
					recursia(element);
				} else if (element.isFile() && ((double)element.length()/(1048576)>1.0)) {
					NetResources netResources = 
						new NetResources();
					netResources.setName(element.getName());
					netResources.setFileSize((int)((double)element.length()/1048576.0));
					netResources.setFileChangeDate(new Date(element.getDate()));
					netResources.setPath(element.getCanonicalPath()); 
					netResources.setServer(element.getServer());
					session.save(netResources);
					out.println(element.getServer()+" \n");
					out.println(element.getContentLength()
								/ (1024 * 1024) + "\t" + element.getName()
								+ "\t" + element.getCanonicalPath()+"\n");
				}
			}
		} catch (SmbException ex) {
			ex.printStackTrace(out);
		} catch(Exception ex){
			ex.printStackTrace(out);
		}
	}
	//clean database before execution update
	private void clean() {
		int rowsAffected = session.createQuery("delete netresources where server = :server")
		.setString("server",root.getServer())
		.executeUpdate();
		out.println("DELETED ROWS "+rowsAffected+" ON SERVER "+root.getServer());
	}
}
